"use client";

import React from "react";
import { Menu, Spin, Tooltip } from "antd";
import { type FC } from "react";
import { FolderOutlined, FileOutlined, CheckCircleOutlined, ClockCircleOutlined } from "@ant-design/icons";
import "./PreviewNavigation.css"; // 导入自定义样式

interface NavigationItem {
  key: string;
  title: string;
  isCompleted?: boolean;
  children?: NavigationItem[];
}

interface PreviewNavigationProps {
  items: NavigationItem[];
  onSelect: (key: string) => void;
  selectedKey?: string;
  isLoading?: boolean;
  defaultOpenKeys?: string[];
}

const PreviewNavigation: FC<PreviewNavigationProps> = ({
  items,
  onSelect,
  selectedKey,
  isLoading = false,
  defaultOpenKeys,
}) => {
  // 将导航项转换为 Menu 项
  const getMenuItems = (navItems: NavigationItem[]) => {
    return navItems.map((item) => {
      if (item.children && item.children.length > 0) {
        // 计算任务的完成状态 - 如果所有子步骤都完成，则任务完成
        const isTaskCompleted = item.children.every(step => step.isCompleted);
        const completedStepsCount = item.children.filter(step => step.isCompleted).length;
        const totalSteps = item.children.length;
        const progressText = `${completedStepsCount}/${totalSteps}`;
        
        // 截断标题，如果超过15个字符
        const truncatedTitle = item.title.length > 15 
          ? `${item.title.substring(0, 15)}...` 
          : item.title;
        
        return {
          key: item.key,
          label: (
            <Tooltip title={`${item.title} (${progressText})`} placement="right">
              <div className="flex items-center justify-between w-full nav-item-container">
                <div className="flex items-center nav-item-title">
                  <FolderOutlined className={`mr-2 ${isTaskCompleted ? 'text-green-500' : 'text-blue-500'}`} />
                  <span className="truncate">{truncatedTitle}</span>
                </div>
                <span className="text-xs text-gray-500 ml-2 nav-item-progress">{progressText}</span>
              </div>
            </Tooltip>
          ),
          children: getMenuItems(item.children),
        };
      }
      
      // 步骤项
      // 截断标题，如果超过18个字符
      const truncatedTitle = item.title.length > 18 
        ? `${item.title.substring(0, 18)}...` 
        : item.title;
        
      return {
        key: item.key,
        label: (
          <Tooltip title={item.title} placement="right">
            <div className="flex items-center justify-between w-full nav-item-container">
              <div className="flex items-center nav-item-title">
                {item.isCompleted ? (
                  <CheckCircleOutlined className="mr-2 text-green-500" />
                ) : (
                  <ClockCircleOutlined className="mr-2 text-orange-500" />
                )}
                <span className={`truncate ${item.isCompleted ? 'text-green-600' : ''}`}>
                  {truncatedTitle}
                </span>
              </div>
            </div>
          </Tooltip>
        ),
      };
    });
  };

  // 获取所有任务的键，用于默认展开
  const getAllTaskKeys = React.useMemo(() => {
    return items.map(item => item.key);
  }, [items]);

  // 获取当前选中项的父级键
  const getParentKey = React.useMemo(() => {
    if (!selectedKey || !selectedKey.includes('-')) return undefined;
    return selectedKey.split('-')[0];
  }, [selectedKey]);

  // 计算默认展开的键
  const computedDefaultOpenKeys = React.useMemo(() => {
    if (defaultOpenKeys) return defaultOpenKeys;
    if (getParentKey) return [getParentKey];
    return getAllTaskKeys;
  }, [defaultOpenKeys, getParentKey, getAllTaskKeys]);

  if (isLoading) {
    return (
      <div className="flex justify-center items-center h-full">
        <Spin tip="加载中..." />
      </div>
    );
  }

  return (
    <Menu
      mode="inline"
      selectedKeys={selectedKey ? [selectedKey] : []}
      defaultOpenKeys={computedDefaultOpenKeys}
      style={{ height: "100%", borderRight: 0 }}
      items={getMenuItems(items)}
      onClick={({ key }) => onSelect(key)}
      className="custom-menu"
    />
  );
};

export default PreviewNavigation;
